package com.open.gen.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

/**
 * FreeMarkers工具类
 */
public class FreeMarkerUtils {

    private static Logger log = LoggerFactory.getLogger(FreeMarkerUtils.class);

    private static Configuration configuration;

    static {
        configuration = new Configuration(Configuration.getVersion());
        configuration.setTemplateUpdateDelay(0);
        configuration.setOutputEncoding("UTF-8");
        configuration.setDefaultEncoding("UTF-8");
        configuration.setNumberFormat("0.##########");
        configuration.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
        configuration.setDateFormat("yyyy-MM-dd");
        configuration.setTimeFormat("HH:mm:ss");
        configuration.setClassicCompatible(true);
        configuration.setLogTemplateExceptions(true);
    }

    // 渲染模版
    public static String renderString(String templateString, Map<String, ?> model) {
        try {
            StringWriter result = new StringWriter();
            Template t = new Template("name", new StringReader(templateString), configuration);
            t.process(model, result);
            return result.toString();
        } catch (Exception e) {
            log.error("Freemarker模版处理发生异常，异常详情：", e);
        }
        return null;
    }

    // 渲染模版
    public static String renderTemplate(Template template, Object model) {
        try {
            StringWriter result = new StringWriter();
            template.process(model, result);
            return result.toString();
        } catch (Exception e) {
            log.error("Freemarker模版处理发生异常，异常详情：", e);
        }
        return null;
    }

}
